package com.ai.chat.controller;

import com.ai.chat.entity.Conversation;
import com.ai.chat.service.ConversationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/conversations")
public class ConversationController {

    @Autowired
    private ConversationService conversationService;

    /**
     * 创建新对话
     */
    @PostMapping
    public ResponseEntity<Conversation> createConversation(@RequestParam String title, Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        Conversation conversation = conversationService.createConversation(userId, title);
        return ResponseEntity.ok(conversation);
    }

    /**
     * 删除对话
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Boolean> deleteConversation(@PathVariable Long id, Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        boolean deleted = conversationService.deleteConversation(userId, id);
        return ResponseEntity.ok(deleted);
    }

    /**
     * 获取用户所有对话
     */
    @GetMapping
    public ResponseEntity<List<Conversation>> getUserConversations(Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        List<Conversation> conversations = conversationService.getUserConversations(userId);
        return ResponseEntity.ok(conversations);
    }

    /**
     * 更新对话标题
     */
    @PutMapping("/{id}/title")
    public ResponseEntity<Conversation> updateConversationTitle(
            @PathVariable Long id,
            @RequestParam String title,
            Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        Conversation updatedConversation = conversationService.updateConversationTitle(userId, id, title);
        return ResponseEntity.ok(updatedConversation);
    }

    /**
     * 获取对话详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Conversation> getConversationById(@PathVariable Long id, Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        Conversation conversation = conversationService.getConversationById(id);
        // 验证对话所有权
        if (!conversation.getUserId().equals(userId)) {
            return ResponseEntity.status(403).build();
        }
        return ResponseEntity.ok(conversation);
    }
}